<template>
  <qh-page-view :title="title">
    <view class="search-box">
      <view class="search-content flex-cn" @click="searchData">
        <text class="qh-rt-single qh-rt-a-zu2432 search-icon"></text>
        <input class="search-input" type="text" disabled />
        <view class="search-btn flex-cn-cn">搜索</view>
      </view>
    </view>
    <searcHistory
      v-model="showHistory"
      :top-distance="88"
      @doSearch="handleSearch"
      ref="historyPopup"
    />

    <waterfallsFlow
      ref="WaterfallRef"
      @updateSKU="generateSKU"
      :wfList="goodsList"
      :updateNum="searchForm.page"
    >
    </waterfallsFlow>
    <!-- <view class="flex-column-100">
              <scroll-view scroll-y="true" class="scroll-view" :lower-threshold="100" :show-scrollbar="false" @scrolltolower="getGoodsList"
                   refresher-enabled @refresherrefresh="pullDownRefresh" :refresher-triggered="isRefresh"
                   refresher-background="transparent">
                   <view class="scroll-view-content">
                        <view class="goods-list-box  flex-spb flex-wrap">
                             <waterfallsFlow ref="WaterfallRef" @updateSKU="generateSKU"
                                 :wfList="goodsList" :updateNum="searchForm.page">
                             </waterfallsFlow>
                             <view class="flex-cn-cn" style="width: 100%;height: 60rpx;">
                                  <view v-if="canLoad && isLoading" class="bottom-message flex-cn-cn">加载中...</view>
                                  <view v-if="!canLoad && !isLoading" class="flex-cn-cn bottom-message">
                                       <view class="line"></view>
                                       <text class="mar_l_10 mar_r_10">没有更多了</text>
                                       <view class="line"></view>
                                  </view>
                             </view>
                        </view>
                   </view>
              </scroll-view>
         </view> -->

    <shopping-pushpins></shopping-pushpins>
    <!-- 选择规格弹窗 -->
    <block v-if="showSelectSku">
      <choose-sku
        :sku="sku"
        :goodsinfo="goods"
        goodsType="1"
        @close="closeSku"
      ></choose-sku>
    </block>

    <SkuDetailsCard
      ref="popupComponent"
      :goodsinfo="goods"
      :BoxStyle="1"
    ></SkuDetailsCard>
  </qh-page-view>
</template>

<script>
const app = getApp().globalData;
//sku的组件
import SkuDetailsCard from "@/components/skuDetails/skuDetails.vue";
//历史搜索的组件
import searcHistory from "./search_history/search_history.vue";
export default {
  components: {
    SkuDetailsCard,
    searcHistory,
  },
  data() {
    return {
      showHistory: false, //search的状态值
      goodsChecked: [],
      animations: [],
      animationIndex: null,
      indexes: [],
      isFocus: false,
      title: "",
      goodsList: [],
      isRefresh: false,
      isLoading: false,
      canLoad: true,
      searchForm: {
        search: "",
        person1: "",
        person2: "",
        person3: "",
        page: 1,
        limit: 100,
      },
      showSelectSku: false,
      goods: {},
      sku: {},
      label_id: "",
    };
  },
  /**
   * @param {Object} options
   * name		分类名称
   * type		分类级别  1、2、3 不传默认为1
   * id		分类id
   */
  async onLoad(options) {
    await this.$onLaunched;
    this.label_id = options.label_id;
    if (options.search == 1) {
      this.$nextTick(() => {
        this.isFocus = true;
      });
      this.title = "搜索商品";
    } else {
      this.title = options.name ? options.name : "商品列表";
      if (options.id) {
        switch (options.type) {
          case "2":
            this.searchForm.person2 = options.id;
            break;
          case "3":
            this.searchForm.person3 = options.id;
            break;
          default:
            this.searchForm.person1 = options.id;
            break;
        }
      }
      //   this.searchData();
    }
    this.getGoodsList();
  },
  onShow() {
    if (this.$refs.WaterfallRef) {
      this.$refs.WaterfallRef.upDate();
    }
  },
  methods: {
    handleOnfocus() {
      const history = uni.getStorageSync("history_list");
      this.showHistory = history && history.length > 0;
    },
    //点击历史的数据
    handleSearch(data) {
      this.searchForm.search = data.value;
      this.searchData();
      console.log("搜索内容:", data.value);
    },
    generateSKU(val) {
      if (val.attribute_state == 2) {
        //SKU的
        this.$refs.popupComponent.handlerApply();

        val.skuDetailList.forEach((item) => {
          const goodsNum = parseInt(item.goods_num);
          item.disabled = goodsNum <= 0;
        });
        this.goods = val;
      }
    },

    goodsNum(goods_num, more_num) {
      let result = 0;
      if (goods_num > 10) {
        if (more_num === 0) {
          result = 100; // 当more_num为0时，返回100%
        } else {
          result = goods_num / more_num;
          if (result <= 1) {
            result = Math.round(result * 100);
          }
        }
      }

      return result;
    },
    buttonClass(item) {
      if (item.num === 0) {
        return true;
      }
      if (item.count > 0) {
        return false;
      }
    },
    //查看商品详情
    toDetail(id) {
      uni.navigateTo({
        url: "/pages/mer/goods/details/details?id=" + id,
      });
    },
    //下拉刷新
    async pullDownRefresh() {
      this.isRefresh = true;
      await this.searchData();
      this.isRefresh = false;
    },

    // 搜索处理函数
    async searchData() {
      uni.navigateTo({
        url: "/pages/mer/goods/search/search?search=1",
      });
 
    },
    //关闭规格弹窗
    closeSku() {
      this.showSelectSku = false;
    },
    //添加商品到购物车
    //     async addToCar(index) {
    //          if (this.goodsList[index].attribute == 2) {
    //               this.goods = {
    //                    ...this.goodsList[index],
    //                    goods_image: this.goodsList[index].path,
    //                    goods_num: 999,
    //               };
    //               this.showSelectSku = true;
    //          } else {
    //               const res = await this.$mutations.setShoppingCar(
    //                    {
    //                         goods_id: this.goodsList[index].goods_id,
    //                         num: 1,
    //                    },
    //                    1
    //               );
    //               if (res) {
    //                    this.showSelectSku = false;
    //               }
    //          }
    //     },
    //点击搜索
    search() {
      uni.navigateTo({
        url: "../product/productList/productList?type=1",
      });
    },
    // 重置搜索相关状态
    resetSearch() {
      this.goodsList = [];
      this.searchForm.page = 1;
      this.canLoad = true;
      this.isLoading = false;

      // 重置瀑布流组件
      if (this.$refs.WaterfallRef) {
        this.$refs.WaterfallRef.upDate();
      }
    },

    getGoodsList() {
      return new Promise(async (resolve) => {
        if (this.isLoading || !this.canLoad) return resolve(false);
        this.isLoading = true;
        this.searchForm = Object.assign(this.searchForm, {
          store_id: this.$store.mallStoreId,
          label_id: this.label_id,
        });
        const { status, data, goods, message } = await this.$request(
          "SmallProgramApi/ShiFu/getLabelGoodList",
          this.searchForm
        );
        if (status != 1)
          return (
            uni.showToast({
              title: message,
              icon: "none",
            }) && resolve(false)
          );

        if (this.goodsPage == 1) {
          this.goodsList = data;
        } else {
          this.goodsList.push.apply(this.goodsList, data);
        }
        this.goodsPage++;
        this.canLoad = data.length < this.goodsLimit ? false : true;

        this.goodsList.forEach((item) => {
          let matchedItem = this.$store.merShoppingGoodsList.find(
            (el) => el.goods_id === item.id
          );
          if (matchedItem) {
            item.num = matchedItem.num;
          } else {
            this.indexes = [];
            item.num = 0;
          }
        });

        this.$nextTick(() => {
          this.isLoading = false;
          resolve(true);
        });
      });
    },
  },
};
</script>

<style lang="scss">
.bottom-message {
  color: #ccc;
  font-size: 24rpx;
  // background-color: #fff;
  width: 100%;
  padding: 10rpx 0;
}

.line {
  width: 40%;
  height: 1px;
  background-color: #ccc;
}

.search-box {
  height: 88rpx;
  padding: 12rpx 24rpx;
  box-sizing: border-box;
  background-color: #ffffff;
  box-shadow: 0 0 16rpx rgba(0, 0, 0, 0.05);
  z-index: 100;

  .search-content {
    height: 100%;
    width: 100%;
    padding: 0 0 0 24rpx;
    border: 2rpx solid var(--primary-color);
    border-radius: 34rpx;
    box-sizing: border-box;
    background-color: #ffffff;

    .search-icon {
      font-size: 28rpx;
      color: #999999;
    }

    .search-input {
      flex: 1;
      font-size: 28rpx;
      line-height: 48rpx;
      color: #333333;
      margin: 0 10rpx;
      height: 48rpx;
    }

    .search-btn {
      width: 124rpx;
      height: 100%;
      font-size: 28rpx;
      color: #ffffff;
      text-align: center;
      line-height: 48rpx;
      background-color: var(--primary-color);
      border-radius: 32rpx;
      margin-right: -1rpx;
    }
  }
}

.scroll-view {
  //     background: linear-gradient(180deg, #ffffff 0%, #f8f8f8 100%);
  background: #f0f2ee;
}
</style>
